package com.jxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxx.anno.CacheFind;
import com.jxx.mapper.UserMapper;
import com.jxx.mapper.UserSecurityMapper;
import com.jxx.pojo.User;
import com.jxx.pojo.UserSecurity;
import com.jxx.service.UserSecurityService;
import com.jxx.vo.ChangePassword;
import com.jxx.vo.SysResult;
import io.micrometer.core.instrument.util.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class UserSecurityServiceImpl implements UserSecurityService {
    @Autowired
    private UserSecurityMapper userSecurityMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * @author LKS
     * @desc 门户端忘记密码，使用密保答案找回密码
     * @param userId
     * @return SysResult
     * @data 2020年12月3日22:43:54
     */
    @Override
    @CacheFind(preKey = "securityQuestion")
    public List<UserSecurity> showSecurityQuestion(Integer userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        List<UserSecurity> securityList = userSecurityMapper.selectList(queryWrapper);
        return securityList;
    }

    /**
     * @author Zcc
     * @desc 修改密码
     * @param   changePassword,request
     * @return SysResult
     * @date 2020年11月21日20:33:54
     */
    @Override
    public SysResult changePassword(ChangePassword changePassword,
                                    HttpServletRequest request) {
        QueryWrapper<UserSecurity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("security_id", changePassword.getSecurityId()).eq("security_answer", changePassword.getSecurityAnswer());
        UserSecurity userSecurity = userSecurityMapper.selectOne(queryWrapper);
        if (userSecurity!=null){
            User user = (User) request.getSession().getAttribute("user");
            SimpleHash sh = new SimpleHash(
                    "MD5",
                    changePassword.getUserPassword(),
                    user.getSalt(),
                    10);
            user.setUserId(user.getUserId()).setUserPassword(sh.toHex());
            userMapper.updateById(user);
            return SysResult.success();
        }
        return SysResult.fail();
    }
}
